﻿'Imports HslCommunication.MQTT
Imports MySql.Data.MySqlClient
Imports System.Runtime.InteropServices
Imports System.Text

'Imports System.Data.SqlClient

Public Class Form1
    Dim WithEvents mClient As MqttClient
    Dim options As MqttConnectOptions
    Dim lpPrevWndProc As IntPtr
    Dim connObject As Object = Nothing
    Dim Pinyin() As String   '存放拼音字符串数组
    Dim IsPinyin As Boolean   '判断拼音对照表是否打开
    Dim loginUserIdList As HashSet(Of String) '存放当前登录用户ID列表
    Dim licenseList As List(Of LicenseInfo)   '授权信息列表
    Private Sub Form1_Disposed(sender As Object, e As EventArgs) Handles Me.Disposed
        ConnClose()
        ' SetWindowLong(Me.Handle, -4, lpPrevWndProc)
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
        'options = New MqttConnectionOptions()
        'Dim c As New MqttCredential
        'c.UserName = "admin"
        'c.Password = "admin"
        'options.CleanSession = True
        'options.ClientId = "rgterwewert787563wffgrd"
        'options.Credentials = c
        'options.IpAddress = "127.0.0.1"
        'options.Port = 1883
        'options.KeepAliveSendInterval = TimeSpan.FromSeconds(60)
        'mqtt = New MqttClient(options)
        ' Dim conn As MySqlConnection = ConnOpen("127.0.0.1", , "x5", , "healthcaresystem")
        ' Dim connection As New MySqlCommand()
        ' conn = New MySqlConnection(mysql)
        ' conn.Open() '打开数据库
        ' Dim s As String = ToHexString(New Byte() {123, 54, 78, 221, 115})
        ' GetAllDatabase(conn)

        ''#Set the form's border style to None
        ' Me.FormBorderStyle = FormBorderStyle.None

        ''#Whatever region that you fill with black will become the glassy region
        ''# (in this example, the entire form becomes transparent)
        ' Me.BackColor = Color.BlueViolet

        ''#Create and populate the blur-behind structure
        ' Dim bb As DWM_BLURBEHIND
        ' bb.dwFlags = DWM_BB_ENABLE
        ' bb.fEnable = True
        ' bb.hRgnBlur = Nothing
        ' bb.fTransitionOnMaximized = True
        ''#Enable the blur-behind effect
        ' DwmEnableBlurBehindWindow(Me.Handle, bb)
        ' Dim h As GCHandle = GCHandle(AddressOf WinDwm.WndProc)
        'lpPrevWndProc = SetWindowLong(Me.Handle, GWL_WNDPROC, AddressOf WinDwm.WndProc)

        'Dim p As String = AppContext.BaseDirectory

        mClient = New MqttClient(Me)
        options = New MqttConnectOptions()
        ComboMqttAddrType.SelectedIndex = 0
        TextMqttUserID.Text = MqttClient.getCpuGuid()
        loginUserIdList = New HashSet(Of String)  '初始化登录用户id列表
        licenseList = New List(Of LicenseInfo)    '初始化授权信息列表
        'Dim val As String = Nothing
        'Dim fn As Integer = FreeFile()
        'FileOpen(fn, AppContext.BaseDirectory, OpenMode.Binary)
        'Input(fn, val)
        'FileClose(fn)
        ' Dim val() As Byte = My.Resources.Pinyin
        ' Dim engb As Encoding = Encoding.GetEncoding("GB2312")
        '  Dim s As String = BytesToBstr(val, "GB2312") ' engb.GetString(val)

        ' Dim s As String = getPychar("鐦攨蕥瘂痖")
    End Sub
    '字节数组转指定编码字符串
    Public Function BytesToBstr(Binary, Unicode) As String
        Dim objstream As Object
        objstream = CreateObject("ADODB.Stream")
        objstream.Type = 1
        objstream.Mode = 3
        objstream.Open()
        objstream.Write(Binary)
        objstream.Position = 0
        objstream.Type = 2
        objstream.Charset = Unicode
        BytesToBstr = objstream.ReadText
        objstream.Close()
    End Function
    Private Sub btnLonig_Click(sender As Object, e As EventArgs) Handles btnLonig.Click
        If btnLonig.Tag = 0 Then
            If TextMqttUserID.TextLength = 0 Then
                MessageBox.Show("客户端唯一标识ID不能为空，请输入!", "客户端标识ID错误", MessageBoxButtons.OK)
                TextMqttUserID.Focus()
            End If
            If TextMySqlAddr.TextLength < 7 Then
                MessageBox.Show("输入的数据库服务器地址不规范，请重新输入!", "IP地址错误", MessageBoxButtons.OK)
                TextMySqlAddr.Text = ""
                TextMySqlAddr.Focus()
            Else
                If Not CheckAddr(TextMySqlAddr.Text) Then
                    MessageBox.Show("输入的数据库服务器地址不规范，请重新输入!", "IP地址错误", MessageBoxButtons.OK)
                    TextMySqlAddr.Text = ""
                    TextMySqlAddr.Focus()
                Else
                    '连接到指定的数据库服务
                    connObject = ConnOpen(TextMySqlAddr.Text, TextMySqlUser.Text, TextMySqlPwd.Text, NumericMySqlPort.Value, "healthcaresystem")
                    If connObject.GetType.Equals(GetType(Exception)) Then
                        Dim ex As Exception = connObject
                        MessageBox.Show(ex.Message, "连接失败", MessageBoxButtons.OK)
                    Else            '连接数据库服务成功
                        If TextMqttAddr.TextLength < 7 Then
                            MessageBox.Show("输入的消息服务器地址不规范，请重新输入!", "IP地址错误", MessageBoxButtons.OK)
                            TextMqttAddr.Text = ""
                            TextMqttAddr.Focus()
                        Else
                            If Not CheckAddr(TextMqttAddr.Text) Then
                                MessageBox.Show("输入的消息服务器地址不规范，请重新输入!", "IP地址错误", MessageBoxButtons.OK)
                                TextMqttAddr.Text = ""
                                TextMqttAddr.Focus()
                            Else
                                options.ClientId = TextMqttUserID.Text
                                options.setMqttVersion(MqttConnectOptions.Version.MQTT_VERSION_3_1_1)
                                options.IpAddress = TextMqttAddr.Text
                                options.Port = NumericMqttPort.Value
                                options.KeepAliveInterval = NumericKeepAlive.Value
                                options.setProperies(60, , , 50)
                                options.CleanSession = RadioCleanSession.Visible
                                options.setCredentials(TextMqttUser.Text, TextMqttPwd.Text)
                                mClient.connectOptions = options   '设置连接选项
                                mClient.ConnectServer()  '连接到MQTT服务器
                            End If
                        End If
                    End If
                End If
            End If
        Else
            mClient.ConnectClose()
        End If
    End Sub
    ''' <summary>
    ''' 检查地址是否合法
    ''' </summary>
    ''' <param name="addr"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function CheckAddr(ByVal addr As String) As Boolean
        '检查IP地址是否合法函数
        Dim intLoop As Integer
        Dim arrAddr() As String = Split(addr, ".") '将输入的IP用"."分割为数组，数组下标从0开始，所以有效IP分割后的数组上界必须为3  

        If UBound(arrAddr) <> 3 Then     '判断IP地址是否不是3段
            Return False
        Else
            For intLoop = 0 To UBound(arrAddr)
                If Not IsNumeric(arrAddr(intLoop)) Then       '检查数组元素中各项是否为数字，如果不是则不是有效IP   
                    Return False
                Else
                    Dim sectionAddr As Int16 = Val(arrAddr(intLoop))   'IP地址指定部分的整数值
                    If sectionAddr > 255 Or sectionAddr < 0 Then       '检查IP数字是否满足IP的取值范围   
                        Return False
                    Else
                        If intLoop = 0 And sectionAddr = 0 Then        '如果索引为0并且这部分的地址为0
                            Return False
                        End If
                    End If
                End If
            Next
        End If
        Return True
    End Function

    Private Sub mClient_connectMqttSuccess(sessionPresent As Boolean) Handles mClient.connectMqttSuccess
        btnLonig.Text = "断开服务"
        btnLonig.Tag = 1
        Dim topics() As String = ManageTopic.getTopics()
        Dim QoS As MqttClient.MqttQoS = MqttClient.MqttQoS.QoS_2
        mClient.subscribe(topics, QoS)
    End Sub

    Private Sub mClient_disConnectSuccess(onlyMqttConnect As Boolean) Handles mClient.disConnectSuccess
        btnLonig.Text = "登陆服务"
        btnLonig.Tag = 0
        ConnClose()
    End Sub

    Private Sub mClient_errorReceiveArrival(controlType As MqttClient.ControlType, errCode As Byte, errMessage As String) Handles mClient.errorReceiveArrival

    End Sub

    Private Sub mClient_publishReceiveArrival(topic As String, message As MqttMessage) Handles mClient.publishReceiveArrival
        Debug.Write(topic + ":")
        Debug.WriteLine(message.getPayloadString)
        Dim json As JSONObject = New JSONObject(message.getPayloadString)
        Select Case topic
            Case ManageTopic.GET_ALL_USER_INFO         '获取全部用户信息

            Case ManageTopic.GET_USER_INFO             '获取用户信息
                getUsers(json)
            Case ManageTopic.SET_USER_INFO             '设置用户信息
                setUsers(json)
            Case ManageTopic.REG_USER_INFO             '注册用户
                regUsers(json)
            Case ManageTopic.REMOVE_USER               '移除用户
                removeUsers(json)
            Case ManageTopic.USER_LOGIN                '用户登录
                userLogin(json)
            Case ManageTopic.USER_LOGOUT               '用户注销
                userLogout(json)
            Case ManageTopic.GET_MEMBER_GROUP          '获取整个家庭成员组信息
                getMemberGroupInfo(json)
            Case ManageTopic.CREATE_MEMBER_GROUP       '创建家庭成员组
                createGroup(json)
            Case ManageTopic.ADD_MEMBER_GROUP          '添加成员到家庭成员组
                addUserToGroup(json)
            Case ManageTopic.REMOVE_MEMBER_GROUP       '从家庭成员组移除成员
                removeMember(json)
            Case ManageTopic.QUERY_MEMBER_GROUP_ID     '查询指定用户绑定的组ID
                queryMemberGroupId(json)
            Case ManageTopic.QUERY_MEMBER_GROUP_DEVICE '查询家庭成员组拥有的设备
                queryMemberGroupDevice(json)
            Case ManageTopic.ADD_HEALTHY_INFO          '添加健康档案信息
                addHealthy(json)
            Case ManageTopic.QUERY_HEALTHY_INFO        '查询健康档案信息
                queryHealthy(json)
            Case ManageTopic.REMOVE_HEALTHY_INFO       '移除指定的健康档案信息
                removeHealthy(json)
            Case ManageTopic.REG_DEVICE                '注册设备
                regDevice(json)
            Case ManageTopic.EDIT_DEVICE               '编辑设备信息
                editDevice(json)
            Case ManageTopic.REMOVE_DEVICE             '移除设备
                removeDevice(json)
            Case ManageTopic.QUERY_DEVICE              '查询设备
                queryDevice(json)
            Case ManageTopic.CONTROL_DEVICE            '设备控制
                controlDevice(json)
            Case ManageTopic.CREATE_LICENSE_INFO       '创建授权信息
                createLicenseInfo(json)
            Case ManageTopic.REVOKE_LICENSE_INFO       '撤销授权
                revokeLicense(json)
        End Select
    End Sub
    ''' <summary>
    ''' 获取用户信息
    ''' </summary>
    ''' <param name="json">用于查询的条件字段
    ''' {"query_field_1":null,"query_field_n":null}
    ''' </param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function getUsers(ByVal json As JSONObject) As Boolean
        If Not json Is Nothing Then
            Dim whereClause As String = Nothing
            Dim keys As Dictionary(Of String, Object).KeyCollection = json.NamesAt()
            For Each key As String In keys    '遍历字典关键字
                Dim val As Object = json.opt(key)
                If whereClause Is Nothing Then
                    If IsNumeric(val) Then    '判断值类型是否为数字
                        whereClause = key & "=" & val
                    Else
                        whereClause = key & "='" & val & "'"
                    End If
                Else
                    If IsNumeric(val) Then   '判断值类型是否为数字
                        whereClause = " AND " & key & "=" & val
                    Else
                        whereClause = " AND " & key & "='" & val & "'"
                    End If
                End If
            Next
            Dim dataReader As Object = OpenTabe(connObject, "userinfo", "UserID", whereClause, "*")
            If dataReader.GetType.Equals(GetType(MySqlDataReader)) Then
                Dim tempReader As MySqlDataReader = dataReader
                Dim resultJson As JSONArray = New JSONArray()
                While tempReader.Read
                    Dim jsonObj As JSONObject = New JSONObject()
                    For i As Int32 = 0 To tempReader.FieldCount - 1
                        Dim key As String = tempReader.GetName(i)
                        Dim val As Object = tempReader.Item(key)
                        jsonObj.put(key, val)
                    Next
                    resultJson.Put(jsonObj) '将数据对象添加到数组
                End While
                tempReader.Close()
                If resultJson Is Nothing Then
                    Dim resultJosn As JSONObject = New JSONObject()
                    resultJosn.put("err_code", 100)
                    resultJosn.put("err_desc", "The specified user information does not exist.")
                    resultJosn.put("system_err", False)
                    If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                        Return False
                    End If
                Else
                    Dim resultJosn As JSONObject = New JSONObject()
                    resultJosn.put("success", resultJson)
                    If mClient.publish(ManageTopic.ACK_USER_INFO, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                        Return True
                    End If
                End If
            Else
                Dim e As MySqlException = dataReader
                Dim resultJosn As JSONObject = New JSONObject()
                resultJosn.put("err_code", e.ErrorCode)
                resultJosn.put("err_desc", e.Message)
                resultJosn.put("system_err", True)
                If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                    Return False
                End If
            End If
        End If
        Return False
    End Function
    ''' <summary>
    ''' 设置用户信息
    ''' </summary>
    ''' <param name="json">
    ''' 包含查询条件及需要设置的用户信息。
    ''' 数据格式：
    ''' {"query":{"query_field_1":null,"query_field_n":null},"content":{"content_field_0":null,"content_field_1":null,"content_field_n":null}}
    ''' 字段说明：(query_field=用于查询的字段名称:查询字段值；content_field=需要设置的内容字段:设置的内容)
    ''' </param>
    ''' <returns>true 成功</returns>
    ''' <remarks></remarks>
    Private Function setUsers(ByVal json As JSONObject) As Boolean
        Dim whereClause As String = Nothing
        Dim keys As Dictionary(Of String, Object).KeyCollection = Nothing
        If json.isKeyName("query") Then
            Dim queryJson As JSONObject = json.optJSONObject("query")
            If Not queryJson Is Nothing Then
                keys = queryJson.NamesAt()        '取得字典关键字列表
                For Each key As String In keys    '遍历字典关键字
                    Dim val As Object = queryJson.opt(key)
                    If whereClause Is Nothing Then
                        If IsNumeric(val) Then    '判断值类型是否为数字
                            whereClause = key & "=" & val
                        Else
                            whereClause = key & "='" & val & "'"
                        End If
                    Else
                        If IsNumeric(val) Then   '判断值类型是否为数字
                            whereClause = " AND " & key & "=" & val
                        Else
                            whereClause = " AND " & key & "='" & val & "'"
                        End If
                    End If
                Next
                If json.isKeyName("content") Then
                    Dim contentJson As JSONObject = json.optJSONObject("content")
                    If Not contentJson Is Nothing Then
                        keys = contentJson.NamesAt()
                        Dim vals() As Object = contentJson.Values.ToArray
                        Dim result As Object = SqlUpdate(connObject, "userinfo", whereClause, keys.ToArray(), vals)
                        If result.GetType.Equals(GetType(Boolean)) Then
                            If mClient.publish(ManageTopic.ACK_SUCCESS, "{""success"":""ok""}", MqttClient.MqttQoS.QoS_2) <> -1 Then
                                Return True
                            End If
                        Else
                            Dim e As MySqlException = result
                            Dim resultJosn As JSONObject = New JSONObject()
                            resultJosn.put("err_code", e.ErrorCode)
                            resultJosn.put("err_desc", e.Message)
                            resultJosn.put("system_err", True)
                            If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                                Return False
                            End If
                        End If
                    End If
                End If
            End If
        Else
            Dim resultJosn As JSONObject = New JSONObject()
            resultJosn.put("err_code", 103)
            resultJosn.put("err_desc", "The parameter is incorrect.")
            resultJosn.put("system_err", False)
            If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                Return False
            End If
        End If
        Return False
    End Function
    ''' <summary>
    ''' 注册用户信息
    ''' </summary>
    ''' <param name="json">
    ''' 需要注册的用户信息。数据格式：
    ''' {"userID":"0000","userName":null,"userPwd":null,"sex":0,"age":0,"phone":null,"mailbox":null,"chatID":null,"chatType":"0","regTime":null,"devId":null}
    ''' </param>
    ''' <remarks></remarks>
    Private Function regUsers(ByVal json As JSONObject) As Boolean
        Dim userId As String = Nothing
        Dim userName As String = Nothing
        Dim userPwd As String = Nothing
        Dim sex As Byte
        Dim age As Byte
        Dim phone As String = Nothing
        Dim mailbox As String = Nothing
        Dim chatID As String = Nothing
        Dim chatType As String = 0
        Dim regTime As String = Nothing
        If json.isKeyName("userName") Then
            userName = json.optString("userName")
            If isField(connObject, "userinfo", "userName", userName) = False Then
                Dim dayTime As Date = Now()
                If json.isKeyName("UserID") Then
                    userId = json.optString("UserID")
                    If isField(connObject, "userinfo", "UserID", userId) Then
                        userId = getPychar(userName) + Format(dayTime, "yyMMddHHmmss")  '用户id=字符串拼音首字母+日期格式字串
                    End If
                Else
                    userId = getPychar(userName) + Format(dayTime, "yyMMddHHmmss") '用户id=字符串拼音首字母+日期格式字串
                End If
                If json.isKeyName("userPwd") Then
                    userPwd = json.optString("userPwd")
                End If
                If json.isKeyName("sex") Then
                    sex = json.getByte("sex")
                Else
                    sex = 0
                End If
                If json.isKeyName("age") Then
                    age = json.getByte("age")
                Else
                    age = 0
                End If
                If json.isKeyName("phone") Then
                    phone = json.optString("phone")
                End If
                If json.isKeyName("mailbox") Then
                    mailbox = json.optString("mailbox")
                End If
                If json.isKeyName("chatID") Then
                    chatID = json.optString("chatID")
                    If json.isKeyName("chatType") Then
                        chatType = json.optInteger("chatType")
                    End If
                End If
                If json.isKeyName("regTime") Then
                    regTime = json.optString("regTime")
                    If (regTime Is Nothing) Then regTime = Format(dayTime, "yyyy/MM/dd HH:mm:ss")
                Else
                    regTime = Format(dayTime, "yyyy/MM/dd HH:mm:ss")
                End If
                Dim fieldList As String = "userID,userName,userPwd,sex,age,phone,mailbox,chatID,chatType,regTime"
                Dim vals() As Object = {userId, userName, userPwd, sex, age, phone, mailbox, chatID, chatType, regTime}
                Dim result As Object = SqlInsert(connObject, "userinfo", fieldList, vals)
                If result.GetType.Equals(GetType(Boolean)) Then
                    If mClient.publish(ManageTopic.ACK_SUCCESS, "{""success"":""ok""}", MqttClient.MqttQoS.QoS_2) <> -1 Then
                        Return True
                    End If
                Else
                    Dim e As MySqlException = result
                    Dim resultJosn As JSONObject = New JSONObject()
                    resultJosn.put("err_code", e.ErrorCode)
                    resultJosn.put("err_desc", e.Message)
                    resultJosn.put("system_err", True)

                    If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                        Return False
                    End If
                End If
            Else
                Dim resultJosn As JSONObject = New JSONObject()
                resultJosn.put("err_code", 200)
                resultJosn.put("err_desc", "The user already exists.")
                resultJosn.put("system_err", False)

                If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                    Return False
                End If
            End If
        Else
            Dim resultJosn As JSONObject = New JSONObject()
            resultJosn.put("err_code", 103)
            resultJosn.put("err_desc", "The parameter is incorrect.")
            resultJosn.put("system_err", False)

            If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                Return False
            End If
        End If
        Return False
    End Function
    ''' <summary>
    ''' 移除指定用户
    ''' </summary>
    ''' <param name="json">用于查询的条件字段{"query_field_1":null,"query_field_n":null}。字段可以是“userID”，“userName”，“phone”，“mailbox”，“chatID”</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function removeUsers(ByVal json As JSONObject) As Boolean
        If Not json Is Nothing Then
            Dim whereClause As String = Nothing
            Dim keys As Dictionary(Of String, Object).KeyCollection = json.NamesAt()
            For Each key As String In keys    '遍历字典关键字
                Dim val As Object = json.opt(key)
                If whereClause Is Nothing Then
                    If IsNumeric(val) Then    '判断值类型是否为数字
                        whereClause = key & "=" & val
                    Else
                        whereClause = key & "='" & val & "'"
                    End If
                Else
                    If IsNumeric(val) Then   '判断值类型是否为数字
                        whereClause = " AND " & key & "=" & val
                    Else
                        whereClause = " AND " & key & "='" & val & "'"
                    End If
                End If
            Next
            Dim userID As String = json.optString("userID")
            If isField(connObject, "binddevice", "userID", userID) Then    '查找绑定列表中释放存在该设备
                SqlDelete(connObject, "binddevice", "userID='" + userID + "'") '删除绑定设备列表中的数据
            End If
            Dim result As Object = SqlDelete(connObject, "userinfo", whereClause)
            If result.GetType.Equals(GetType(Boolean)) Then
                If mClient.publish(ManageTopic.ACK_SUCCESS, "{""success"":""ok""}", MqttClient.MqttQoS.QoS_2) <> -1 Then
                    Return True
                End If
            Else
                Dim e As MySqlException = result
                Dim resultJosn As JSONObject = New JSONObject()
                resultJosn.put("err_code", e.ErrorCode)
                resultJosn.put("err_desc", e.Message)
                resultJosn.put("system_err", True)

                If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                    Return False
                End If
            End If
        End If
        Return False
    End Function
    ''' <summary>
    ''' 获取成员组信息
    ''' </summary>
    ''' <param name="json">
    ''' 用于查询的条件字段
    ''' {"query_field_1":null,"query_field_n":null}
    ''' 如：{"groupID":"6756"}或{"GroupName":"null"}
    ''' </param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function getMemberGroupInfo(ByVal json As JSONObject) As Boolean
        If Not json Is Nothing Then
            Dim whereClause As String = Nothing
            Dim keys As Dictionary(Of String, Object).KeyCollection = json.NamesAt()
            For Each key As String In keys    '遍历字典关键字
                Dim val As Object = json.opt(key)
                If whereClause Is Nothing Then
                    If IsNumeric(val) Then    '判断值类型是否为数字
                        whereClause = key & "=" & val
                    Else
                        whereClause = key & "='" & val & "'"
                    End If
                Else
                    If IsNumeric(val) Then   '判断值类型是否为数字
                        whereClause = " AND " & key & "=" & val
                    Else
                        whereClause = " AND " & key & "='" & val & "'"
                    End If
                End If
            Next
            Dim dataReader As Object = OpenTabe(connObject, "memberinfoview", "memberID", whereClause, "*")
            If dataReader.GetType.Equals(GetType(MySqlDataReader)) Then
                Dim tempReader As MySqlDataReader = dataReader
                Dim resultJson As JSONArray = New JSONArray()
                While tempReader.Read
                    Dim jsonObj As JSONObject = New JSONObject()
                    For i As Int32 = 0 To tempReader.FieldCount - 1
                        Dim key As String = tempReader.GetName(i)
                        Dim val As Object = tempReader.Item(key)
                        jsonObj.put(key, val)
                    Next
                    resultJson.Put(jsonObj) '将数据对象添加到数组
                End While
                tempReader.Close()

                If resultJson.Count = 0 Then
                    Dim resultJosn As JSONObject = New JSONObject()
                    resultJosn.put("err_code", 101)
                    resultJosn.put("err_desc", "Find the specified family member information for in the family group.")
                    resultJosn.put("system_err", False)

                    If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                        Return False
                    End If
                Else
                    Dim resultJosn As JSONObject = New JSONObject()
                    resultJosn.put("success", resultJson)
                    If mClient.publish(ManageTopic.ACK_MEMBER_GROUP, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                        Return True
                    End If
                End If
            Else
                Dim e As MySqlException = dataReader
                Dim resultJosn As JSONObject = New JSONObject()
                resultJosn.put("err_code", e.ErrorCode)
                resultJosn.put("err_desc", e.Message)
                resultJosn.put("system_err", True)

                If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                    Return False
                End If
            End If
        End If
        Return False
    End Function
    ''' <summary>
    ''' 创建家庭成员组
    ''' </summary>
    ''' <param name="json">
    ''' 需要创建的家庭成员组数据。数据格式：
    ''' {"GroupName":"组名称","CreaterID":"创建者id","Area":"家庭组所在位置(物理地址)"}
    ''' </param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function createGroup(ByVal json As JSONObject) As Boolean
        Dim GroupID As String = Nothing
        Dim GroupName As String = Nothing
        Dim CreaterID As String = Nothing
        Dim Area As String = Nothing
        If json.isKeyName("CreaterID") Then
            CreaterID = json.optString("CreaterID")

            If isField(connObject, "familyGroup", "CreaterID", CreaterID) Then
                Dim resultJosn As JSONObject = New JSONObject()
                resultJosn.put("err_code", 102)
                resultJosn.put("err_desc", "The current user already belongs to the creator of another family member group.")
                resultJosn.put("system_err", False)

                If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                    Return False
                End If
            Else
                If isField(connObject, "userinfo", "userID", CreaterID) Then
                    If json.isKeyName("GroupName") Then
                        GroupName = json.optString("GroupName")
                    End If
                    GroupID = getNewGroupId()
                    If json.isKeyName("Area") Then
                        Area = json.optString("Area")
                    End If
                    Dim fieldList As String = "GroupID,GroupName,CreaterID,Area"
                    Dim vals() As Object = {GroupID, GroupName, CreaterID, Area}
                    Dim result As Object = SqlInsert(connObject, "familyGroup", fieldList, vals)   '添加组信息
                    If result.GetType.Equals(GetType(Boolean)) Then
                        vals = {GroupID, CreaterID}
                        result = SqlInsert(connObject, "familymembers", "groupID,memberID", vals)  '将当前用户添加到家庭成员组
                        If result.GetType.Equals(GetType(Boolean)) Then
                            If mClient.publish(ManageTopic.ACK_SUCCESS, "{""success"":""ok""}", MqttClient.MqttQoS.QoS_2) <> -1 Then
                                Return True
                            End If
                        Else
                            SqlDelete(connObject, "group", GroupID)
                        End If
                    Else
                        Dim e As MySqlException = result
                        Dim resultJosn As JSONObject = New JSONObject()
                        resultJosn.put("err_code", e.ErrorCode)
                        resultJosn.put("err_desc", e.Message)
                        resultJosn.put("system_err", True)

                        If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                            Return False
                        End If
                    End If
                Else
                    Dim resultJosn As JSONObject = New JSONObject()
                    resultJosn.put("err_code", 105)
                    resultJosn.put("err_desc", "The family member group creator is not registered.")
                    resultJosn.put("system_err", False)

                    If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                        Return False
                    End If
                End If
            End If
        Else
            Dim resultJosn As JSONObject = New JSONObject()
            resultJosn.put("err_code", 103)
            resultJosn.put("err_desc", "The parameter is incorrect.")
            resultJosn.put("system_err", False)

            If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                Return False
            End If
        End If
        Return False
    End Function
    ''' <summary>
    ''' 添加成员到家庭成员组
    ''' </summary>
    ''' <param name="json">
    ''' 用于查询和添加的数据。格式：
    ''' {"CreaterID":"创建者id","memberID":"要添加的成员id"}
    ''' </param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function addUserToGroup(ByVal json As JSONObject) As Boolean
        If json.isKeyName("CreaterID") And json.isKeyName("memberID") Then
            Dim CreaterID As String = json.optString("CreaterID")  '家庭成员组创建者id
            Dim MemberID As String = json.optString("memberID") '要添加的成员id
            Dim dataReader As Object = OpenTabe(connObject, "familyGroup", "GroupID", "CreaterID='" + CreaterID + "'", , True) '打开指定创建者关联的组数据
            If dataReader.GetType.Equals(GetType(MySqlDataReader)) Then
                Dim tempReader As MySqlDataReader = dataReader
                If tempReader.HasRows Then
                    tempReader.Read()
                    Dim GroupID As String = tempReader.GetString("GroupID")
                    tempReader.Close()
                    If isField(connObject, "userinfo", "userID", MemberID) Then
                        Dim fieldList As String = "groupID,memberID"
                        Dim vals() As Object = {GroupID, MemberID}
                        Dim result As Object = SqlInsert(connObject, "familymembers", fieldList, vals)   '添加成员到家庭成员组
                        If result.GetType.Equals(GetType(Boolean)) Then
                            If mClient.publish(ManageTopic.ACK_SUCCESS, "{""success"":""ok""}", MqttClient.MqttQoS.QoS_2) <> -1 Then
                                Return True
                            End If
                        Else
                            Dim e As MySqlException = result
                            Dim resultJosn As JSONObject = New JSONObject()
                            resultJosn.put("err_code", e.ErrorCode)
                            resultJosn.put("err_desc", e.Message)
                            resultJosn.put("system_err", True)

                            If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                                Return False
                            End If
                        End If
                    Else
                        Dim resultJosn As JSONObject = New JSONObject()
                        resultJosn.put("err_code", 104)
                        resultJosn.put("err_desc", "The member to be added is not registered.")
                        resultJosn.put("system_err", False)

                        If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                            Return False
                        End If
                    End If
                Else
                    Dim resultJosn As JSONObject = New JSONObject()
                    resultJosn.put("err_code", 106)
                    resultJosn.put("err_desc", "The family member group information associated with the specified creator ID was not found.")
                    resultJosn.put("system_err", False)

                    If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                        Return False
                    End If
                End If
            Else
                Dim e As MySqlException = dataReader
                Dim resultJosn As JSONObject = New JSONObject()
                resultJosn.put("err_code", e.ErrorCode)
                resultJosn.put("err_desc", e.Message)
                resultJosn.put("system_err", True)

                If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                    Return False
                End If
            End If
        Else
            Dim resultJosn As JSONObject = New JSONObject()
            resultJosn.put("err_code", 103)
            resultJosn.put("err_desc", "The parameter is incorrect.")
            resultJosn.put("system_err", False)

            If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                Return False
            End If
        End If
        Return False
    End Function
    ''' <summary>
    ''' 从家庭成员组移除成员
    ''' </summary>
    ''' <param name="json">
    ''' 用于查询的条件字段{"query_field":null,"memberID":"被移除的成员id"}。字段可以是“CreaterID”或“memberID”。
    ''' 如果“query_field”=“CreaterID”，“memberID”字段必须设置；
    ''' 如果“query_field”=“memberID”，“memberID”字段可以去除。
    ''' </param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function removeMember(ByVal json As JSONObject) As Boolean
        If Not json Is Nothing Then
            Dim MemberID As String = Nothing
            Dim whereClause As String = Nothing
            If json.isKeyName("CreaterID") Then  '判断组创建者id是从存在
                Dim CreaterID As String = json.optString("CreaterID")
                MemberID = json.optString("memberID")
                Dim dataReader As Object = OpenTabe(connObject, "familyGroup", "GroupID", "CreaterID='" + CreaterID + "'", , True) '打开指定创建者关联的组数据
                If dataReader.GetType.Equals(GetType(MySqlDataReader)) Then
                    Dim tempReader As MySqlDataReader = dataReader
                    If tempReader.HasRows Then
                        tempReader.Read()
                        Dim GroupID As String = tempReader.GetString("GroupID")
                        tempReader.Close()
                        whereClause = "groupID='" + GroupID + "' AND memberID='" + MemberID + "'"
                    Else
                        Dim resultJosn As JSONObject = New JSONObject()
                        resultJosn.put("err_code", 106)
                        resultJosn.put("err_desc", "The family member group information associated with the specified creator ID was not found.")
                        resultJosn.put("system_err", False)

                        If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                            Return False
                        End If
                    End If
                End If
            ElseIf json.isKeyName("memberID") Then
                MemberID = json.optString("memberID")
                whereClause = "memberID='" + MemberID + "'"
            End If
            Dim result As Object = SqlDelete(connObject, "familymembers", whereClause)
            If result.GetType.Equals(GetType(Boolean)) Then
                If mClient.publish(ManageTopic.ACK_SUCCESS, "{""success"":""ok""}", MqttClient.MqttQoS.QoS_2) <> -1 Then
                    Return True
                End If
            Else
                Dim e As MySqlException = result
                Dim resultJosn As JSONObject = New JSONObject()
                resultJosn.put("err_code", e.ErrorCode)
                resultJosn.put("err_desc", e.Message)
                resultJosn.put("system_err", True)

                If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                    Return False
                End If
            End If
        End If
        Return False
    End Function
    ''' <summary>
    ''' 查询家庭成员组id
    ''' </summary>
    ''' <param name="json">
    ''' 一个已绑定到家庭成员组的用户id的json格式数据。格式：{"memberID":"成员id"}
    ''' </param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function queryMemberGroupId(ByVal json As JSONObject) As Boolean
        If (json.isKeyName("memberID")) Then
            Dim memberID As String = json.optString("memberID")
            If Not memberID Is Nothing Then
                Dim dataReader As Object = OpenTabe(connObject, "familymembers", "groupID", "memberID='" + memberID + "'", "", True)
                If dataReader.GetType.Equals(GetType(MySqlDataReader)) Then
                    Dim tempReader As MySqlDataReader = dataReader
                    If tempReader.HasRows Then
                        tempReader.Read()
                        Dim GroupID As String = tempReader.GetString("groupID")
                        tempReader.Close()
                        If (Not GroupID Is Nothing AndAlso GroupID.Length > 0) Then
                            If mClient.publish(ManageTopic.ACK_MEMBER_GROUP_ID, "{""groupID"":""" + GroupID + """}", MqttClient.MqttQoS.QoS_2) <> -1 Then
                                Return True
                            End If
                        Else
                            Dim resultJosn As JSONObject = New JSONObject()
                            resultJosn.put("err_code", 108)
                            resultJosn.put("err_desc", "No home member group binding information was found for the brake user.")
                            resultJosn.put("system_err", False)

                            If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                                Return False
                            End If
                        End If
                    End If
                Else
                    Dim e As MySqlException = dataReader
                    Dim resultJosn As JSONObject = New JSONObject()
                    resultJosn.put("err_code", e.ErrorCode)
                    resultJosn.put("err_desc", e.Message)
                    resultJosn.put("system_err", True)

                    If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                        Return False
                    End If
                End If
            Else
                Dim resultJosn As JSONObject = New JSONObject()
                resultJosn.put("err_code", 107)
                resultJosn.put("err_desc", "User ID cannot be empty.")
                resultJosn.put("system_err", False)

                If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                    Return False
                End If
            End If
        Else
            Dim resultJosn As JSONObject = New JSONObject()
            resultJosn.put("err_code", 103)
            resultJosn.put("err_desc", "The parameter is incorrect.")
            resultJosn.put("system_err", False)

            If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                Return False
            End If
        End If
        Return False
    End Function
    ''' <summary>
    ''' 查询家庭成员组设备
    ''' </summary>
    ''' <param name="json"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function queryMemberGroupDevice(ByVal json As JSONObject) As Boolean
        If (json.isKeyName("groupID")) Then
            Dim groupID As String = json.optString("groupID")
            If Not groupID Is Nothing Then
                '打开指定组id下的设备信息列表（设备id不重复）
                Dim dataReader As Object = OpenTabe(connObject, "memberinfoview", "devId", "groupID='" + groupID + "'", "groupID,devId")
                If dataReader.GetType.Equals(GetType(MySqlDataReader)) Then
                    Dim tempReader As MySqlDataReader = dataReader
                    Dim resultJson As JSONArray = New JSONArray()
                    If tempReader.HasRows Then
                        While tempReader.Read
                            Dim jsonObj As JSONObject = New JSONObject()
                            For i As Int32 = 0 To tempReader.FieldCount - 1
                                Dim key As String = tempReader.GetName(i)
                                Dim val As Object = tempReader.Item(key)
                                jsonObj.put(key, val)
                            Next
                            resultJson.Put(jsonObj) '将数据对象添加到数组
                        End While
                        tempReader.Close()
                        If mClient.publish(ManageTopic.ACK_MEMBER_GROUP_DEVICE, resultJson.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                            Return True
                        End If
                    End If
                Else
                    Dim e As MySqlException = dataReader
                    Dim resultJosn As JSONObject = New JSONObject()
                    resultJosn.put("err_code", e.ErrorCode)
                    resultJosn.put("err_desc", e.Message)
                    resultJosn.put("system_err", True)

                    If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                        Return False
                    End If
                End If
            Else
                Dim resultJosn As JSONObject = New JSONObject()
                resultJosn.put("err_code", 109)
                resultJosn.put("err_desc", "Group ID cannot be empty.")
                resultJosn.put("system_err", False)

                If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                    Return False
                End If
            End If
        Else
            Dim resultJosn As JSONObject = New JSONObject()
            resultJosn.put("err_code", 103)
            resultJosn.put("err_desc", "The parameter is incorrect.")
            resultJosn.put("system_err", False)

            If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                Return False
            End If
        End If
        Return False
    End Function
    ''' <summary>
    ''' 添加用户健康档案
    ''' </summary>
    ''' <param name="json">
    ''' 需要添加进健康档案的数据。格式：
    ''' {"userID":"用户id","ItemID":"检测项目ID","ItemName":"检测项目名称","result":"检测结果","remarks":"备注"}
    ''' </param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function addHealthy(ByVal json As JSONObject) As Boolean
        If json.isKeyName("userID") And json.isKeyName("ItemID") Then
            Dim userID As String = json.optString("userID")
            If isField(connObject, "userinfo", "userID", userID) Then
                Dim ItemID As String = json.optString("ItemID")
                Dim ItemName As String = json.optString("ItemName")
                Dim resultHealthy As String = json.optString("result")
                Dim remarks As String = json.optString("remarks")
                Dim fieldList As String = "userID,ItemID,ItemName,result,remarks"
                Dim vals() As Object = {userID, ItemID, ItemName, resultHealthy, remarks}
                Dim result As Object = SqlInsert(connObject, "healthyinfo", fieldList, vals)
                If result.GetType.Equals(GetType(Boolean)) Then
                    If mClient.publish(ManageTopic.ACK_SUCCESS, "{""success"":""ok""}", MqttClient.MqttQoS.QoS_2) <> -1 Then
                        Return True
                    End If
                Else
                    Dim e As MySqlException = result
                    Dim resultJosn As JSONObject = New JSONObject()
                    resultJosn.put("err_code", e.ErrorCode)
                    resultJosn.put("err_desc", e.Message)
                    resultJosn.put("system_err", True)

                    If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                        Return False
                    End If
                End If
            Else
                Dim resultJosn As JSONObject = New JSONObject()
                resultJosn.put("err_code", 100)
                resultJosn.put("err_desc", "The specified user information does not exist.")
                resultJosn.put("system_err", False)

                If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                    Return False
                End If
            End If
        Else
            Dim resultJosn As JSONObject = New JSONObject()
            resultJosn.put("err_code", 103)
            resultJosn.put("err_desc", "The parameter is incorrect.")
            resultJosn.put("system_err", False)

            If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                Return False
            End If
        End If
        Return False
    End Function
    ''' <summary>
    ''' 查询指定的健康档案
    ''' </summary>
    ''' <param name="json">
    ''' 执行查询的条件数据。格式：
    ''' {"userID":"查询的用户id","ItemID":"检测项目id","time_slot":{"start_time":"00:00","end_time":"23:00"}}
    ''' 其中"userID"为必填项；"ItemID","time_slot"为可选项
    ''' </param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function queryHealthy(ByVal json As JSONObject) As Boolean
        If Not json Is Nothing And json.isKeyName("userID") Then
            Dim whereClause As String = "userID='" + json.optString("userID") + "'"
            If json.isKeyName("ItemID") Then
                whereClause += " AND ItemID='" + json.optString("ItemID") + "'"
            End If
            If json.isKeyName("time_slot") Then
                Dim timeJson As JSONObject = json.optJSONObject("time_slot")
                If Not timeJson Is Nothing Then
                    Dim start_time As String = Nothing, end_time As String = Nothing
                    If timeJson.isKeyName("start_time") And timeJson.isKeyName("end_time") Then
                        whereClause += " AND checkTime BETWEEN'" + json.optString("start_time") + "' AND '" + json.optString("end_time") + "'"
                    ElseIf timeJson.isKeyName("start_time") = False Then
                        whereClause += " AND checkTime='" + json.optString("start_time") + "'"
                    ElseIf timeJson.isKeyName("end_time") = False Then
                        whereClause += " AND checkTime='" + json.optString("end_time") + "'"
                    End If
                End If
            End If
            Dim dataReader As Object = OpenTabe(connObject, "healthyinfo", whereClause, "userID", True)
            If dataReader.GetType.Equals(GetType(MySqlDataReader)) Then
                Dim tempReader As MySqlDataReader = dataReader
                Dim resultJson As JSONArray = New JSONArray()
                If tempReader.HasRows Then
                    While tempReader.Read
                        Dim jsonObj As JSONObject = New JSONObject()
                        For i As Int32 = 0 To tempReader.FieldCount - 1
                            Dim key As String = tempReader.GetName(i)
                            Dim val As Object = tempReader.Item(key)
                            jsonObj.put(key, val)
                        Next
                        resultJson.Put(jsonObj) '将数据对象添加到数组
                    End While
                    tempReader.Close()
                    If mClient.publish(ManageTopic.ACK_HEALTHY_INFO, resultJson.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                        Return True
                    End If
                End If
            Else
                Dim e As MySqlException = dataReader
                Dim resultJosn As JSONObject = New JSONObject()
                resultJosn.put("err_code", e.ErrorCode)
                resultJosn.put("err_desc", e.Message)
                resultJosn.put("system_err", True)

                If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                    Return False
                End If
            End If
        Else
            Dim resultJosn As JSONObject = New JSONObject()
            resultJosn.put("err_code", 103)
            resultJosn.put("err_desc", "The parameter is incorrect.")
            resultJosn.put("system_err", False)

            If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                Return False
            End If
        End If
        Return False
    End Function
    ''' <summary>
    ''' 删除指定的健康档案
    ''' </summary>
    ''' <param name="json">
    ''' 执行删除的条件数据。格式：
    ''' {"userID":"查询的用户id","ItemID":"检测项目id","time_slot":{"start_time":"00:00","end_time":"23:00"}}
    ''' 其中"userID"为必填项；"ItemID","time_slot"为可选项
    ''' </param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function removeHealthy(ByVal json As JSONObject) As Boolean
        If Not json Is Nothing And json.isKeyName("userID") Then
            Dim whereClause As String = "userID='" + json.optString("userID") + "'"
            If json.isKeyName("ItemID") Then
                whereClause += " AND ItemID='" + json.optString("ItemID") + "'"
            End If
            If json.isKeyName("time_slot") Then
                Dim timeJson As JSONObject = json.optJSONObject("time_slot")
                If Not timeJson Is Nothing Then
                    Dim start_time As String = Nothing, end_time As String = Nothing
                    If timeJson.isKeyName("start_time") And timeJson.isKeyName("end_time") Then
                        whereClause += " AND checkTime BETWEEN'" + json.optString("start_time") + "' AND '" + json.optString("end_time") + "'"
                    ElseIf timeJson.isKeyName("start_time") = False Then
                        whereClause += " AND checkTime='" + json.optString("start_time") + "'"
                    ElseIf timeJson.isKeyName("end_time") = False Then
                        whereClause += " AND checkTime='" + json.optString("end_time") + "'"
                    End If
                End If
            End If
            Dim result As Object = SqlDelete(connObject, "healthyinfo", whereClause)
            If result.GetType.Equals(GetType(Boolean)) Then
                If mClient.publish(ManageTopic.ACK_SUCCESS, "{""success"":""ok""}", MqttClient.MqttQoS.QoS_2) <> -1 Then
                    Return True
                End If
            Else
                Dim e As MySqlException = result
                Dim resultJosn As JSONObject = New JSONObject()
                resultJosn.put("err_code", e.ErrorCode)
                resultJosn.put("err_desc", e.Message)
                resultJosn.put("system_err", True)

                If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                    Return False
                End If
            End If
        Else
            Dim resultJosn As JSONObject = New JSONObject()
            resultJosn.put("err_code", 103)
            resultJosn.put("err_desc", "The parameter is incorrect.")
            resultJosn.put("system_err", False)

            If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                Return False
            End If
        End If
        Return False
    End Function
    ''' <summary>
    ''' 用户登录
    ''' </summary>
    ''' <param name="json">登录信息。数据:
    ''' {"userID":"用户ID","userPwd":"登录密码"}、{"phone":"用户注册手机","userPwd":"登录密码"},{"mailbox":"注册邮箱","userPwd":"登录密码"}或{"chatID":"聊天账号","userPwd":"登录密码"}
    ''' </param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function userLogin(json As JSONObject) As Boolean
        Dim whereClause As String = Nothing
        If json.isKeyName("userID") Then
            whereClause = "userID='" + json.optString("userID") + "'"
        ElseIf json.isKeyName("userName") Then
            whereClause = "userName='" + json.optString("userName") + "'"
        ElseIf json.isKeyName("phone") Then
            whereClause = "phone='" + json.optString("phone") + "'"
        ElseIf json.isKeyName("mailbox") Then
            whereClause = "mailbox='" + json.optString("mailbox") + "'"
        ElseIf json.isKeyName("chatID") Then
            whereClause = "chatID='" + json.optString("chatID") + "'"
        End If
        Dim dataReader As Object = OpenTabe(connObject, "userinfo", whereClause, "userID", True)
        If dataReader.GetType.Equals(GetType(MySqlDataReader)) Then
            Dim tempReader As MySqlDataReader = dataReader
            If tempReader.HasRows Then
                tempReader.Read()
                Dim pwd As String = tempReader.GetString("userPwd")
                If pwd.Equals(json.optString("userPwd")) Then
                    Dim resultJosn As JSONObject = New JSONObject()
                    For i As Int32 = 0 To tempReader.FieldCount - 1
                        Dim key As String = tempReader.GetName(i)
                        Dim val As Object = tempReader.Item(key)
                        If key.Equals("userID") Then
                            loginUserIdList.Add(val)   '将当前登录用户存储（后续控制时需要使用）
                        End If
                        resultJosn.put(key, val)
                    Next
                    If mClient.publish(ManageTopic.ACK_LOGIN_SUCCESS, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                        Return True
                    End If
                Else
                    Dim resultJosn As JSONObject = New JSONObject()
                    resultJosn.put("err_code", 202)
                    resultJosn.put("err_desc", "User password error.")
                    resultJosn.put("system_err", False)

                    If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                        Return False
                    End If
                End If
                tempReader.Close()
            Else
                Dim resultJosn As JSONObject = New JSONObject()
                resultJosn.put("err_code", 201)
                resultJosn.put("err_desc", "The user is not registered.")
                resultJosn.put("system_err", False)

                If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                    Return False
                End If
            End If
        Else
            Dim e As MySqlException = dataReader
            Dim resultJosn As JSONObject = New JSONObject()
            resultJosn.put("err_code", e.ErrorCode)
            resultJosn.put("err_desc", e.Message)
            resultJosn.put("system_err", True)

            If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                Return False
            End If
        End If
        Return False
    End Function
    ''' <summary>
    ''' 注销用户
    ''' </summary>
    ''' <param name="json">{"userID":"用户ID"}</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function userLogout(json As JSONObject) As Boolean
        Dim ok As Boolean = False
        If loginUserIdList.Count > 0 Then
            If json.isKeyName("userID") Then
                Dim id = json.optString("userID")
                ok = loginUserIdList.Remove(id)
                If ok Then
                    If mClient.publish(ManageTopic.ACK_SUCCESS, "{""success"":""ok""}", MqttClient.MqttQoS.QoS_2) <> -1 Then
                        Return True
                    End If
                End If
            Else
                Dim resultJosn As JSONObject = New JSONObject()
                resultJosn.put("err_code", 103)
                resultJosn.put("err_desc", "The parameter is incorrect.")
                resultJosn.put("system_err", False)

                If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                    Return False
                End If
            End If
        Else
            Dim resultJosn As JSONObject = New JSONObject()
            resultJosn.put("err_code", 206)
            resultJosn.put("err_desc", "User not logged in.")
            resultJosn.put("system_err", False)

            If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                Return False
            End If
        End If
        Return False
    End Function
    ''' <summary>
    ''' 设备注册
    ''' </summary>
    ''' <param name="json">
    ''' 包含设备信息的数据，格式：
    ''' {userID:"用户ID","devID":"设备ID","devName":"名称","devType":"类型","regType":"注册类型"}
    ''' </param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function regDevice(json As JSONObject) As Boolean
        If json.isKeyName("devID") Then
            Dim devId As String = json.optString("devID")
            Dim userID As String = json.optInteger("userID")
            If devId Is Nothing Or devId.Length = 0 Or userID Is Nothing Or userID.Length = 0 Then
                Dim resultJosn As JSONObject = New JSONObject()
                resultJosn.put("err_code", 203)
                resultJosn.put("err_desc", "Device cannot be empty.")
                resultJosn.put("system_err", False)

                If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                    Return False
                End If
            Else
                If isField(connObject, "device", "devID", devId) Then    '设备已经注册
                    Dim resultJosn As JSONObject = New JSONObject()
                    resultJosn.put("err_code", 204)
                    resultJosn.put("err_desc", "The device is registered.")
                    resultJosn.put("system_err", False)

                    If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                        Return False
                    End If
                Else
                    If json.isKeyName("devName") = False Then
                        Dim resultJosn As JSONObject = New JSONObject()
                        resultJosn.put("err_code", 103)
                        resultJosn.put("err_desc", "The parameter is incorrect.")
                        resultJosn.put("system_err", False)

                        If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                            Return False
                        End If
                    Else
                        Dim devName As String = json.optString("devName")
                        If devName Is Nothing AndAlso devName.Length = 0 Then
                            Dim resultJosn As JSONObject = New JSONObject()
                            resultJosn.put("err_code", 205)
                            resultJosn.put("err_desc", "Device name cannot be empty.")
                            resultJosn.put("system_err", False)

                            If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                                Return False
                            End If
                        Else
                            Dim devType As Integer
                            Dim regType As Integer
                            If json.isKeyName("devType") Then
                                devType = json.optInteger("devType")
                            End If
                            If json.isKeyName("regType") Then
                                regType = json.optInteger("regType")
                            End If
                            Dim fieldList As String = "devID,devName,devType,regType"
                            Dim vals() As Object = {devId, devName, devType, regType}
                            Dim result As Object = SqlInsert(connObject, "device", fieldList, vals)
                            If result.GetType.Equals(GetType(Boolean)) Then
                                If regType = 0 Then
                                    '绑定到个人
                                    result = SqlInsert(connObject, "binddevice", "userID='" & userID & "'", "devId", devId)
                                    If result.GetType.Equals(GetType(Boolean)) Then
                                        If mClient.publish(ManageTopic.ACK_SUCCESS, "{""success"":""ok""}", MqttClient.MqttQoS.QoS_2) <> -1 Then
                                            Return True
                                        End If
                                    Else
                                        Dim e As MySqlException = result
                                        Dim resultJosn As JSONObject = New JSONObject()
                                        resultJosn.put("err_code", e.ErrorCode)
                                        resultJosn.put("err_desc", e.Message)
                                        resultJosn.put("system_err", True)

                                        If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                                            Return False
                                        End If
                                    End If
                                Else
                                    If mClient.publish(ManageTopic.ACK_SUCCESS, "{""success"":""ok""}", MqttClient.MqttQoS.QoS_2) <> -1 Then
                                        Return True
                                    End If
                                End If
                            Else
                                Dim e As MySqlException = result
                                Dim resultJosn As JSONObject = New JSONObject()
                                resultJosn.put("err_code", e.ErrorCode)
                                resultJosn.put("err_desc", e.Message)
                                resultJosn.put("system_err", True)

                                If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                                    Return False
                                End If
                            End If
                        End If
                    End If
                End If
            End If
        Else
            Dim resultJosn As JSONObject = New JSONObject()
            resultJosn.put("err_code", 103)
            resultJosn.put("err_desc", "The parameter is incorrect.")
            resultJosn.put("system_err", False)

            If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                Return False
            End If
        End If
        Return False
    End Function
    ''' <summary>
    ''' 修改设备信息
    ''' </summary>
    ''' <param name="json">
    ''' 包含设备ID及需要修改信息字段,格式：
    ''' {"devID":"设备ID","content":{"devName":"设备名称","devType":"类型","regType":"注册类型"}}（修改的内容字段全为可选，但只是需要包含一个修改字段）
    ''' </param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function editDevice(json As JSONObject) As Boolean
        If json.isKeyName("devID") And json.isKeyName("content") Then
            Dim devId As String = json.optString("devID")
            If devId Is Nothing AndAlso devId.Length = 0 Then
                Dim resultJosn As JSONObject = New JSONObject()
                resultJosn.put("err_code", 203)
                resultJosn.put("err_desc", "Device cannot be empty.")
                resultJosn.put("system_err", False)

                If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                    Return False
                End If
            Else
                Dim contentJson As JSONObject = json.optJSONObject("content")
                If contentJson Is Nothing Then
                    Dim resultJosn As JSONObject = New JSONObject()
                    resultJosn.put("err_code", 204)
                    resultJosn.put("err_desc", "At least one modified data field is required.")
                    resultJosn.put("system_err", False)

                    If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                        Return False
                    End If
                Else
                    Dim keys As Dictionary(Of String, Object).KeyCollection = contentJson.NamesAt
                    Dim vals() As Object = contentJson.Values.ToArray
                    Dim result As Object = SqlUpdate(connObject, "device", "devID='" + devId + "'", keys.ToArray(), vals)
                    If result.GetType.Equals(GetType(Boolean)) Then
                        If mClient.publish(ManageTopic.ACK_SUCCESS, "{""success"":""ok""}", MqttClient.MqttQoS.QoS_2) <> -1 Then
                            Return True
                        End If
                    Else
                        Dim e As MySqlException = result
                        Dim resultJosn As JSONObject = New JSONObject()
                        resultJosn.put("err_code", e.ErrorCode)
                        resultJosn.put("err_desc", e.Message)
                        resultJosn.put("system_err", True)

                        If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                            Return False
                        End If
                    End If
                End If
            End If
        Else
            Dim resultJosn As JSONObject = New JSONObject()
            resultJosn.put("err_code", 103)
            resultJosn.put("err_desc", "The parameter is incorrect.")
            resultJosn.put("system_err", False)

            If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                Return False
            End If
        End If
        Return False
    End Function
    ''' <summary>
    ''' 删除设备
    ''' </summary>
    ''' <param name="json">执行删除的条件，数据：{"devID":"设备id"}</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function removeDevice(json As JSONObject) As Boolean
        If json.isKeyName("devID") Then
            Dim devId As String = json.optString("devID")
            If devId Is Nothing AndAlso devId.Length = 0 Then
                Dim resultJosn As JSONObject = New JSONObject()
                resultJosn.put("err_code", 203)
                resultJosn.put("err_desc", "Device cannot be empty.")
                resultJosn.put("system_err", False)

                If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                    Return False
                End If
            Else
                If isField(connObject, "binddevice", "devID", devId) Then    '查找绑定列表中释放存在该设备
                    SqlDelete(connObject, "binddevice", "devID='" + devId + "'") '删除绑定设备列表中的数据
                End If
                Dim result As Object = SqlDelete(connObject, "device", "devID='" + devId + "'")
                If result.GetType.Equals(GetType(Boolean)) Then
                    If mClient.publish(ManageTopic.ACK_SUCCESS, "{""success"":""ok""}", MqttClient.MqttQoS.QoS_2) <> -1 Then  '删除成功
                        Return True
                    End If
                Else
                    Dim e As MySqlException = result
                    Dim resultJosn As JSONObject = New JSONObject()
                    resultJosn.put("err_code", e.ErrorCode)
                    resultJosn.put("err_desc", e.Message)
                    resultJosn.put("system_err", True)

                    If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                        Return False
                    End If
                End If
            End If
        Else
            Dim resultJosn As JSONObject = New JSONObject()
            resultJosn.put("err_code", 103)
            resultJosn.put("err_desc", "The parameter is incorrect.")
            resultJosn.put("system_err", False)

            If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                Return False
            End If
        End If
        Return False
    End Function
    ''' <summary>
    ''' 查询设备
    ''' </summary>
    ''' <param name="json">需要查询设备的条件数据。条件字段可以是"devID","devName","devType"或"regType"</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function queryDevice(json As JSONObject) As Boolean
        If Not json Is Nothing Then
            Dim whereClause As String = Nothing
            Dim keys As Dictionary(Of String, Object).KeyCollection = json.NamesAt()
            For Each key As String In keys    '遍历字典关键字
                Dim val As Object = json.opt(key)
                If whereClause Is Nothing Then
                    If IsNumeric(val) Then    '判断值类型是否为数字
                        whereClause = key & "=" & val
                    Else
                        whereClause = key & "='" & val & "'"
                    End If
                Else
                    If IsNumeric(val) Then   '判断值类型是否为数字
                        whereClause = " AND " & key & "=" & val
                    Else
                        whereClause = " AND " & key & "='" & val & "'"
                    End If
                End If
            Next
            Dim dataReader As Object = OpenTabe(connObject, "device", whereClause, "devID", True)
            If dataReader.GetType.Equals(GetType(MySqlDataReader)) Then
                Dim tempReader As MySqlDataReader = dataReader
                Dim resultJson As JSONArray = New JSONArray()
                While tempReader.Read
                    Dim jsonObj As JSONObject = New JSONObject()
                    For i As Int32 = 0 To tempReader.FieldCount - 1
                        Dim key As String = tempReader.GetName(i)
                        Dim val As Object = tempReader.Item(key)
                        jsonObj.put(key, val)
                    Next
                    resultJson.Put(jsonObj) '将数据对象添加到数组
                End While
                tempReader.Close()

                If resultJson.Count = 0 Then
                    Dim resultJosn As JSONObject = New JSONObject()
                    resultJosn.put("err_code", 205)
                    resultJosn.put("err_desc", "Device information was not found under the specified condition.")
                    resultJosn.put("system_err", False)

                    If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                        Return False
                    End If
                Else
                    Dim resultJosn As JSONObject = New JSONObject()
                    resultJosn.put("success", resultJson)
                    If mClient.publish(ManageTopic.ACK_DEVICE_INFO, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                        Return True
                    End If
                End If
            Else
                Dim e As MySqlException = dataReader
                Dim resultJosn As JSONObject = New JSONObject()
                resultJosn.put("err_code", e.ErrorCode)
                resultJosn.put("err_desc", e.Message)
                resultJosn.put("system_err", True)

                If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                    Return False
                End If
            End If
        End If
        Return False
    End Function
    ''' <summary>
    ''' 客户端发起控制设备请求（在这里需要验证设备绑定的用户，如果是当前用户对象，直接准许使用；如果是第三方用户，需要提前获取到设备所有者授权码；如果未注册，禁用设备）
    ''' </summary>
    ''' <param name="json">
    ''' {"userID":"使用者ID","devID":"设备ID","licenseID":"设备拥有者授权码"}
    ''' </param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function controlDevice(json As JSONObject) As Boolean
        If Not json Is Nothing Then
            If json.isKeyName("userID") And json.isKeyName("devID") Then
                Dim userID As String = json.optString("userID")
                Dim devID As String = json.optString("devID")
                If (userID Is Nothing AndAlso userID.Length = 0) Or (devID Is Nothing AndAlso devID.Length = 0) Then
                    Dim resultJosn As JSONObject = New JSONObject()
                    resultJosn.put("err_code", 207)
                    resultJosn.put("err_desc", "User ID or device ID cannot be empty.")
                    resultJosn.put("system_err", False)

                    If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                        Return False
                    End If
                Else
                    If json.isKeyName("licenseID") And licenseList.Count > 0 Then    '判断是否包含授权字段及授权列表是否有授权信息
                        Dim licenseID As String = json.optString("licenseID")
                        If isLicenseDev(licenseID, devID) Then '授权信息与设备匹配
                            If mClient.publish(ManageTopic.ACK_SUCCESS, "{""success"":""ok""}", MqttClient.MqttQoS.QoS_2) <> -1 Then  '成功
                                Return True
                            End If
                        Else  '授权信息与设备不匹配
                            Dim resultJosn As JSONObject = New JSONObject()
                            resultJosn.put("err_code", 208)
                            resultJosn.put("err_desc", "The authorization information does not match the device.")
                            resultJosn.put("system_err", False)

                            If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                                Return False
                            End If
                        End If
                    Else   '无授权信息，表示为本系统设备
                        Dim whereClause As String = "userID='" + userID + "' AND devID='" + devID + "'"
                        If isField(connObject, "binddevice", whereClause) Then
                            If mClient.publish(ManageTopic.ACK_SUCCESS, "{""success"":""ok""}", MqttClient.MqttQoS.QoS_2) <> -1 Then  '成功
                                Return True
                            End If
                        End If
                    End If
                End If
            Else
                Dim resultJosn As JSONObject = New JSONObject()
                resultJosn.put("err_code", 103)
                resultJosn.put("err_desc", "The parameter is incorrect.")
                resultJosn.put("system_err", False)

                If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                    Return False
                End If
            End If
        End If
        Return False
    End Function
    ''' <summary>
    ''' 创建授权信息
    ''' </summary>
    ''' <param name="json">参数数据格式
    ''' {"userID":"使用者ID","devID":"设备ID"}
    ''' </param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function createLicenseInfo(json As JSONObject) As Boolean
        If Not json Is Nothing Then
            If json.isKeyName("userID") And json.isKeyName("devID") Then
                Dim userID As String = json.optString("userID")
                Dim devID As String = json.optString("devID")
                Dim licenseID As String = Guid.NewGuid.ToString()
                licenseList.Add(New LicenseInfo(licenseID, userID, devID))
                If mClient.publish(ManageTopic.ACK_CREATE_LICENSE_INFO, "{""licenseID"":""" + licenseID + """}", MqttClient.MqttQoS.QoS_2) <> -1 Then  '成功
                    Return True
                End If
            Else
                Dim resultJosn As JSONObject = New JSONObject()
                resultJosn.put("err_code", 103)
                resultJosn.put("err_desc", "The parameter is incorrect.")
                resultJosn.put("system_err", False)

                If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                    Return False
                End If
            End If
        End If
        Return False
    End Function
    ''' <summary>
    ''' 撤销授权信息
    ''' </summary>
    ''' <param name="json">参数格式：{"licenseID":"授权ID"}</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function revokeLicense(json As JSONObject) As Boolean
        If Not json Is Nothing Then
            If json.isKeyName("licenseID") Then
                Dim licenseID As String = json.optString("licenseID")
                For i As Integer = 0 To licenseList.Count - 1
                    Dim license As LicenseInfo = licenseList.Item(i)
                    If license.LicenseID.Equals(licenseID) Then
                        licenseList.RemoveAt(i)
                        If mClient.publish(ManageTopic.ACK_SUCCESS, "{""success"":""ok""}", MqttClient.MqttQoS.QoS_2) <> -1 Then  '成功
                            Return True
                        End If
                    End If
                Next
            Else
                Dim resultJosn As JSONObject = New JSONObject()
                resultJosn.put("err_code", 103)
                resultJosn.put("err_desc", "The parameter is incorrect.")
                resultJosn.put("system_err", False)

                If mClient.publish(ManageTopic.ACK_ERROR, resultJosn.toString, MqttClient.MqttQoS.QoS_2) <> -1 Then
                    Return False
                End If
            End If
        End If
        Return False
    End Function
    ''' <summary>
    ''' 设备与授权信息匹配
    ''' </summary>
    ''' <param name="licenseID">授权id</param>
    ''' <param name="devID">设备id</param>
    ''' <returns>true 匹配；false 不匹配</returns>
    ''' <remarks></remarks>
    Private Function isLicenseDev(ByVal licenseID As String, ByVal devID As String) As Boolean
        If licenseList.Count > 0 Then
            'licenseList.Item
            For i As Integer = 0 To licenseList.Count - 1
                Dim license As LicenseInfo = licenseList.Item(i)
                If license.LicenseID.Equals(licenseID) Then
                    If license.DeviceID.Equals(devID) Then
                        Return True
                    Else
                        Return False
                    End If
                End If
            Next
        End If
        Return False
    End Function
    ''' <summary>
    ''' 获取新的组id
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function getNewGroupId() As String
        Dim dataReader As Object = OpenTabe(connObject, "familyGroup", "GroupID", , "GroupID")
        Dim newGroupId As Int32 = 1   '将新组id初始化为1
        If dataReader.GetType.Equals(GetType(MySqlDataReader)) Then
            Dim tempReader As MySqlDataReader = dataReader
            Dim GroupIDs() As String = Nothing
            While tempReader.Read
                If GroupIDs Is Nothing Then
                    ReDim GroupIDs(0)
                Else
                    ReDim GroupIDs(GroupIDs.Length)
                End If
                GroupIDs(GroupIDs.Length - 1) = tempReader.GetString("GroupID")
            End While
            tempReader.Close()
            If Not GroupIDs Is Nothing Then
                Dim isRepeat As Boolean = False
                Do
                    For intex As Integer = 0 To GroupIDs.Length - 1
                        If Val(GroupIDs(intex)) = newGroupId Then
                            isRepeat = True  '重复
                            Exit For '跳出循环
                        End If
                    Next
                    If isRepeat Then   '重复后+1继续下一次比对
                        newGroupId += 1
                    Else     '不重复后处理结果然后跳出Do循环
                        Exit Do
                    End If
                    isRepeat = False
                Loop
            End If
        End If
        Return Strings.StrDup(10 - newGroupId.ToString.Length, "0") & newGroupId     '处理返回值，不足10位在前面补0
    End Function
    ''' <summary>
    ''' 获取汉字拼音第一字母 
    ''' </summary>
    ''' <param name="str">要获取拼音首字母的字符串</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Function getPychar(ByVal str As String) As String
        Dim pys As String = ""
        For i As Int32 = 0 To str.Length - 1
            Dim as_char As String = str.Substring(i, 1)
            Dim tmp As Integer
            Dim py As String = ""
            tmp = 65536 + Asc(as_char)
            If (tmp >= 45217 And tmp <= 45252) Then
                py = "A"
            ElseIf (tmp >= 45253 And tmp <= 45760) Then
                py = "B"
            ElseIf (tmp >= 45761 And tmp <= 46317) Then
                py = "C"
            ElseIf (tmp >= 46318 And tmp <= 46825) Then
                py = "D"
            ElseIf (tmp >= 46826 And tmp <= 47009) Then
                py = "E"
            ElseIf (tmp >= 47010 And tmp <= 47296) Then
                py = "F"
            ElseIf (tmp >= 47297 And tmp <= 47613) Then
                py = "G"
            ElseIf (tmp >= 47614 And tmp <= 48118) Then
                py = "H"
            ElseIf (tmp >= 48119 And tmp <= 49061) Then
                py = "J"
            ElseIf (tmp >= 49062 And tmp <= 49323) Then
                py = "K"
            ElseIf (tmp >= 49324 And tmp <= 49895) Then
                py = "L"
            ElseIf (tmp >= 49896 And tmp <= 50370) Then
                py = "M"
            ElseIf (tmp >= 50371 And tmp <= 50613) Then
                py = "N"
            ElseIf (tmp >= 50614 And tmp <= 50621) Then
                py = "O"
            ElseIf (tmp >= 50622 And tmp <= 50905) Then
                py = "P"
            ElseIf (tmp >= 50906 And tmp <= 51386) Then
                py = "Q"
            ElseIf (tmp >= 51387 And tmp <= 51445) Then
                py = "R"
            ElseIf (tmp >= 51446 And tmp <= 52217) Then
                py = "S"
            ElseIf (tmp >= 52218 And tmp <= 52697) Then
                py = "T"
            ElseIf (tmp >= 52698 And tmp <= 52979) Then
                py = "W"
            ElseIf (tmp >= 52980 And tmp <= 53688) Then
                py = "X"
            ElseIf (tmp >= 53689 And tmp <= 54480) Then
                py = "Y"
            ElseIf (tmp >= 54481 And tmp <= 55289) Then
                py = "Z"
            Else '如果不是中文，则不处理 
                If (tmp >= 65 And tmp <= 90) Or tmp >= 97 And tmp <= 122 Or IsNumeric(as_char) Then
                    py = as_char
                Else
                    If (IsPinyin = False) Then
                        Pinyin = My.Resources.pyzmtab.Split(vbLf)   '载入资源字符串
                        IsPinyin = True
                    End If
                    For index As Integer = 0 To Pinyin.Length - 1
                        Dim s As String = Pinyin(index)
                        If s.IndexOf(as_char) > 0 Then
                            py = s.Substring(0, 1)
                            Exit For
                        End If
                    Next
                End If
            End If
            pys += py
        Next
        Return pys
    End Function
End Class
